﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using yq.ControllerBase;
using System.Collections;
using System.Web;
using System.IO;
using LitJson;
using yq.Model.Logic;

namespace yq.Controller.Home
{
    public class PublicReuseController : BaseController
    {
        public ActionResult HeadTitle()
        {
            return PartialView();
        }

        public ActionResult RowLeft(bool back=false)
        {
            return PartialView(back);
        }

        /// <summary>
        /// 判断是否有权限
        /// </summary>
        /// <returns></returns>
        [NoPurviewFilter()]
        public ActionResult Purview(string action, string controller, string area)
        {
            yq.Dictionary.ReturnValue<string> rv = new Dictionary.ReturnValue<string>();
            PurviewPage page = new PurviewPage();

            if (IsPurview(action, controller, area, out page))
            {
                rv.True(page.PwId);
            }
            else
            {
                rv.False("您没有这个功能的操作权限");
            }

            return Json(rv);
        }

        /// <summary>
        /// 显示图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public FileContentResult ShowImg(string id, int maxWidth=0, int maxHeight=0, int quality=-1)
        {
            var service=yq.GetService.Create<yq.IService.IUpload>();

            byte[] by = new byte[1];
            if(maxWidth==0||maxHeight==0||quality==-1)
            {
                by=service.DownFile(id);
            }else
            {
                by=service.DownFileImg(id,maxWidth,maxHeight,quality);
            }

            return File(by, "image");
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public FileContentResult DownFile(string id)
        {
            var info = yq.Model.Logic.SysFile.Load(id);

            if (info.IsLoad)
            {
                var by = yq.GetService.Create<yq.IService.IUpload>().DownFile(id);
                return File(by, "appliction/octet-stream", info.FlieName);
            }
            else
            {
                return File(new byte[1],"text");
            }
        }

        /// <summary>
        /// 编辑器用上传图片
        /// </summary>
        /// <returns></returns>
        public ActionResult Upload()
        {
            //定义允许上传的文件扩展名
            Hashtable extTable = new Hashtable();
            extTable.Add("image", "gif,jpg,jpeg,png,bmp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

            //最大文件大小
            int maxSize = 1000000;

            HttpPostedFileBase imgFile = Request.Files["imgFile"];

            if (imgFile == null)
            {
                showError("请选择文件。");
            }

            String fileName = imgFile.FileName;
            String fileExt = Path.GetExtension(fileName).ToLower();

            String dirName = Request.QueryString["dir"];
            if (String.IsNullOrEmpty(dirName))
            {
                dirName = "image";
            }
            if (!extTable.ContainsKey(dirName))
            {
                showError("目录名不正确。");
            }
            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                showError("上传文件大小超过限制。");
            }

            if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。");
            }

            //上传文件
            yq.Model.Logic.SysFile file = new Model.Logic.SysFile()
            {
                 DownCount=0,
                 Extension = fileExt,
                 FileSize = imgFile.ContentLength,
                 FlieName = fileName,
                 ModelId = Request["ModelId"]!=null?Request["ModelId"].ToString():""
            };
            byte[] bt = new byte[1];
            bt = new byte[imgFile.InputStream.Length];
            imgFile.InputStream.Read(bt, 0, bt.Length);
            var rv = yq.GetService.Create<yq.IService.IUpload>().UpFile(bt, file);

         
            //返回
            Hashtable hash = new Hashtable();
            if (rv.Status == Dictionary.ReturnEnum.Yes)
            {
                hash["error"] = 0;
                hash["url"] = Url.Content("~/home/PublicReuse/ShowImg?id=" + rv.Value);
            }
            else
            {
                hash = showError("上传失败");
            }

            return Json(hash, "text/html; charset=UTF-8");
        }

        /// <summary>
        /// 上传控件提交
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadFile(string modelId = "")
        {
            string fileName = "error";
            if (this.Request.Files.Count != 0)
            {
                var imgFile = this.Request.Files[0];

                fileName = imgFile.FileName;
                String fileExt = Path.GetExtension(fileName).ToLower();

                //上传文件
                yq.Model.Logic.SysFile file = new Model.Logic.SysFile()
                {
                    DownCount = 0,
                    Extension = fileExt,
                    FileSize = imgFile.ContentLength,
                    FlieName = fileName,
                    ModelId = modelId
                };
                byte[] bt = new byte[1];
                bt = new byte[imgFile.InputStream.Length];
                imgFile.InputStream.Read(bt, 0, bt.Length);
                var rv = yq.GetService.Create<yq.IService.IUpload>().UpFile(bt, file);

                if (rv.Status == Dictionary.ReturnEnum.Yes)
                {
                    fileName = rv.Value;
                    return this.Content(fileName);
                }
            }

            return this.Content(fileName);
        }

        /// <summary>
        /// 内部方法
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private Hashtable showError(string message)
        {
            Hashtable hash = new Hashtable();
            hash["error"] = 1;
            hash["message"] = message;
            return hash;
        }
    }
}
